import { defineStore } from 'pinia'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { SystemConfigApi } from '@/api/mqtt/systemconfig'

const { wsCache } = useCache()

interface MqttConfigVO {
  sysKey: string
  sysValue: string
}

export const useMqttConfigStore = defineStore('mqtt-config', {
  state: () => ({
    configs: [] as MqttConfigVO[]
  }),
  getters: {
    getValue:
      (state) =>
      (key: string): string => {
        const config = state.configs.find((item) => item.sysKey === key)
        return config ? config.sysValue : ''
      }
  },
  actions: {
    async setMqttConfigAction() {
      try {
        const sysConfig = await SystemConfigApi.list()
        console.log('mqttSysconfig:', JSON.stringify(sysConfig))
        this.configs = sysConfig // 更新state
        wsCache.set(CACHE_KEY.MQTT_CONFIG, this.configs) // 缓存
      } catch (error) {
        console.error('Failed to fetch MQTT config:', error)
      }
    }
  }
})

// 如果不需要额外包装，可以直接导出
export default useMqttConfigStore
